package com.tools.taglib;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 * 用于读取多语言信息的jsp标签
 * 
 * 2013-8-15 下午5:33:29
 * 
 * @author <a href="xinyuan.guo@baozun.cn">郭馨元</a>
 * 
 */
public class Tag4I18nJson extends TagSupport {

	private static final long serialVersionUID = 1445876295618172720L;

	private final static Logger log = LoggerFactory.getLogger(Tag4I18nJson.class);

	private Object val;

	private String lang;

	@Override
	public int doStartTag() throws JspException {
		JspWriter out = this.pageContext.getOut();
		try {
			try {
				JSONObject jo = JSONObject.fromObject(val);
				if (jo != null) {
					String langStr = getLangStr();
					if (jo.has(langStr)) {
						out.print(jo.get(langStr));
					} else
						throw new JspException("i18n resolve Error: not accpetable lang");
				} else {
					throw new JspException("i18n resolve Error: tag val is null");
				}
			} catch (JSONException ioe) {
				out.print(val);
				log.warn("trying to resolve a non i18n value {}", val);
			}
		} catch (IOException e) {
			throw new JspException("i18n resolve Error: IO error");
		}
		return SKIP_BODY;
	}

	private String getLangStr() {
		if (StringUtils.isNotBlank(lang)) {
			return lang;
		} else {
			ServletRequest request = this.pageContext.getRequest();
			if (request != null && request instanceof HttpServletRequest) {
				HttpServletRequest req = (HttpServletRequest) request;
				Locale resolveLocale = RequestContextUtils.getLocale(req);
				if (resolveLocale != null)
					return resolveLocale.toString();
			}
			return null;
		}
	}

	public int doAfterBody() throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}

	public Object getVal() {
		return val;
	}

	public void setVal(Object val) throws JspException {
		if (val != null) {
			try {
				this.val = ExpressionEvaluatorManager.evaluate("val", val.toString(), Object.class, this, pageContext);
			} catch (JspException e) {
				this.val = val;
			}
		} else
			this.val = "";
	}

	public String getLang() {
		return lang;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}
}